#include "gd32w51x.h"
#include "stdint.h"
#include "stdio.h"
#include "DevicesBlower.h"

void vBlowerInit(void)
{
    timer_oc_parameter_struct timer_ocinitpara = {0};
    timer_parameter_struct timer_initpara = {0};

    /* enable the GPIO clock */
    rcu_periph_clock_enable(RCU_GPIOA);

    /*configure TIMERx CHx as alternate function*/
    gpio_mode_set(GPIOA, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO_PIN_5);
    gpio_output_options_set(GPIOA, GPIO_OTYPE_PP, GPIO_OSPEED_25MHZ, GPIO_PIN_5);
    gpio_af_set(GPIOA, GPIO_AF_2, GPIO_PIN_5);


    /* enable the TIMER clock */
    rcu_periph_clock_enable(RCU_TIMER4);
    /* deinit a TIMER */
    timer_deinit(TIMER4);
    /* initialize TIMER init parameter struct */
    timer_struct_para_init(&timer_initpara);
    /* TIMER4 configuration */
    timer_initpara.prescaler         = BLOWER_PWM_PRESCALER - 1;
    timer_initpara.period            = BLOWER_PWM_PERIOD;
    timer_initpara.alignedmode       = TIMER_COUNTER_EDGE;
    timer_initpara.counterdirection  = TIMER_COUNTER_UP;
    timer_initpara.clockdivision     = TIMER_CKDIV_DIV1;
    timer_initpara.repetitioncounter = 0;
    timer_init(TIMER4, &timer_initpara);


    /* initialize TIMER channel output parameter struct */
    timer_channel_output_struct_para_init(&timer_ocinitpara);
    /* configure TIMER channel output function */
    timer_ocinitpara.outputstate  = TIMER_CCX_ENABLE;
    timer_ocinitpara.outputnstate = TIMER_CCXN_DISABLE;
    timer_ocinitpara.ocpolarity   = TIMER_OC_POLARITY_HIGH;
    timer_ocinitpara.ocnpolarity  = TIMER_OCN_POLARITY_HIGH;
    timer_ocinitpara.ocidlestate  = TIMER_OC_IDLE_STATE_LOW;
    timer_ocinitpara.ocnidlestate = TIMER_OCN_IDLE_STATE_LOW;
    timer_channel_output_config(TIMER4, TIMER_CH_3, &timer_ocinitpara);

    /* CH1 configuration in PWM mode0, duty cycle 0% */
    timer_channel_output_pulse_value_config(TIMER4, TIMER_CH_3, 0);
    timer_channel_output_mode_config(TIMER4, TIMER_CH_3, TIMER_OC_MODE_PWM0);
    timer_channel_output_shadow_config(TIMER4, TIMER_CH_3, TIMER_OC_SHADOW_DISABLE);


    /* auto-reload preload enable */
    timer_auto_reload_shadow_enable(TIMER4);
     /* TIMER4 counter enable */
    timer_enable(TIMER4);

    cBlowerSetSpeed(0.0f);
}
